package com.spring.shops.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.spring.shops.dao.TzNoticeMapper;
import com.spring.shops.model.dto.NoticeDTO;
import com.spring.shops.model.entity.TzNotice;
import com.spring.shops.model.result.IPageIndexImg;
import com.spring.shops.model.result.ServerResponseEntityVoid;
import com.spring.shops.model.vo.NoticeVo;
import com.spring.shops.service.NoticeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements NoticeService {
    @Autowired
    private TzNoticeMapper tzNoticeMapper;

    @Override
    public int deletedById(Long id) {
        int i = tzNoticeMapper.deleteByPrimaryKey(id);
        return i;

    }

    @Override
    public ServerResponseEntityVoid<IPageIndexImg<NoticeVo>> page(NoticeDTO noticeDTO) {
        //获取当前页码
        Long current = noticeDTO.getCurrent();
        //获取每页显示的条数
        Long size= noticeDTO.getSize();
        //设置分页初始值
        PageHelper.startPage(Math.toIntExact(current), Math.toIntExact(size));
        //调用mapper层进行分页查询
        Page<TzNotice> indexNoticePage=tzNoticeMapper.page(noticeDTO);
        //创建IPageIndexImg对象
        IPageIndexImg<NoticeVo> iPageIndexImg=new IPageIndexImg<>();
        iPageIndexImg.setSize(size);
        iPageIndexImg.setTotal(indexNoticePage.getTotal());
        iPageIndexImg.setCurrent(current);
        iPageIndexImg.setPages(indexNoticePage.getTotal()/size+1);
        //获取所有记录
        List<TzNotice> result = indexNoticePage.getResult();
        List<NoticeVo> data = new ArrayList<>();

        //属性拷贝
        for (TzNotice tzIndexNotice : result) {
            NoticeVo noticeVo=new NoticeVo();

            BeanUtils.copyProperties(tzIndexNotice,
                    noticeVo);
            //加入集合中

            data.add(noticeVo);
        }
        iPageIndexImg.setRecords(data);
        //返回结果集
        return ServerResponseEntityVoid.success(iPageIndexImg);
    }
    @Override
    public int  save(TzNotice tzNotice) {
        tzNotice.setPublishTime(new Date());
        tzNotice.setUpdateTime(new Date());
        tzNotice.setShopId((long)1);
        int insert = tzNoticeMapper.insert(tzNotice);
        System.out.println(insert);
        return insert;
    }

    @Override
    public int update(TzNotice tzNotice) {
        int i = tzNoticeMapper.updateByPrimaryKeySelective(tzNotice);
        return i;
    }

    @Override
    public TzNotice selectById(Long id) {


        System.out.println(id);

        TzNotice tzNotice = tzNoticeMapper.selectById(id);

        return tzNotice;
    }


}




